<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="名称" prop="sfproductName">
        <el-input
          v-model="queryParams.sfproductName"
          placeholder="请输入名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="是否自产" prop="ifSelfProduced">
        <el-select v-model="queryParams.ifSelfProduced" placeholder="请选择是否自产" clearable>
          <el-option
            v-for="dict in dict.type.lw_self_produced"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="型号" prop="model">
        <el-input
          v-model="queryParams.model"
          placeholder="请输入型号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="参数" prop="parameter">
        <el-input
          v-model="queryParams.parameter"
          placeholder="请输入参数"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['sfproduct:sfproduct:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['sfproduct:sfproduct:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['sfproduct:sfproduct:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-upload2"
          size="mini"
          @click="handleExport"
          v-hasPermi="['sfproduct:sfproduct:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="sfproductList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
<!--      <el-table-column label="id" align="center" prop="sfproductId" sortable/>-->
      <el-table-column label="名称" align="center" prop="sfproductName" />
      <el-table-column label="是否自产" align="center" prop="ifSelfProduced">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.lw_self_produced" :value="scope.row.ifSelfProduced"/>
        </template>
      </el-table-column>
      <el-table-column label="型号" align="center" prop="model" />
      <el-table-column label="参数" align="center" prop="parameter" />
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-document"
            :style="{ display: scope.row.ifSelfProduced==1?'none':'' }"
            @click="getMaterials(scope.row.sfproductId)"
            v-hasPermi="['sfproduct:sfproduct:table']"
          >元件清单</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['sfproduct:sfproduct:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['sfproduct:sfproduct:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <el-drawer
      :visible.sync="table"
      direction="rtl"
      size="50%">
      <el-button
        type="primary"
        icon="el-icon-plus"
        size="mini"
        @click="materialAdd"
        v-hasPermi="['sfproduct:table:add']"
      >新增</el-button>
      <el-button
        type="warning"
        icon="el-icon-download"
        size="mini"
        @click="handleImport"
      >导入</el-button>
      <el-button
        type="danger"
        icon="el-icon-delete"
        size="mini"
        @click="overAgain"
      >清空</el-button>
      <el-table :data="gridData">
<!--        <el-table-column property="materialId" align="center" label="原材料id"></el-table-column>-->
        <el-table-column label="计数" align="center">
          <template slot-scope="scope">
            {{ scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column property="name" align="center" label="器件名称"></el-table-column>
        <el-table-column property="materialNumber" align="center" label="物料编号"></el-table-column>
        <el-table-column property="model" align="center" label="型号/规格"></el-table-column>
        <el-table-column property="encapsulation" align="center" label="封装"></el-table-column>
        <el-table-column property="quantity" align="center" label="数量"></el-table-column>
        <el-table-column property="bitNumber" align="center" label="位号"></el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="materialUpdate(scope.row)"
              v-hasPermi="['sfproduct:table:edit']"
            >修改</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="materialDelete(scope.row)"
              v-hasPermi="['sfproduct:table:remove']"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-drawer>

    <!-- 添加或修改半成品对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="名称" prop="sfproductName">
          <el-input v-model="form.sfproductName" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="是否自产" prop="ifSelfProduced">
          <el-radio-group v-model="form.ifSelfProduced">
            <el-radio
              v-for="dict in dict.type.lw_self_produced"
              :key="dict.value"
               :label="dict.value"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="型号" prop="model">
          <el-input v-model="form.model" placeholder="请输入型号" />
        </el-form-item>
        <el-form-item label="参数" prop="parameter">
          <el-input v-model="form.parameter" placeholder="请输入参数" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input type="textarea" v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 添加或修改原材料对话框 -->
    <el-dialog :title="matTitle" :visible.sync="matOpen" width="500px" append-to-body>
      <el-form ref="matForm" :model="matForm" :rules="rules" label-width="80px">
        <el-form-item label="元件id" prop="sfproductId" v-show="false"> <!--v-show="false"-->
          <el-input v-model="matForm.sfproductId" />
        </el-form-item>
        <el-form-item label="物料编号" prop="materialNumber" >
          <el-select v-model="matForm.materialId" filterable placeholder="请选择" :disabled = "selectable">
            <el-option
              v-for="item in materials"
              :key="item.materialId"
              :label="item.materialNumber"
              :value="item.materialId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="数量" prop="quantity">
          <el-input v-model="matForm.quantity" placeholder="请输入数量" />
        </el-form-item>
        <el-form-item label="位号" prop="bitNumber">
          <el-input v-model="matForm.bitNumber" placeholder="请输入位号" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitMatForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 用户导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px">
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <div class="el-upload__tip" slot="tip">
<!--          <el-checkbox v-model="upload.updateSupport" />是否更新已经存在的用户数据-->
<!--          <el-link type="info" style="font-size:12px" @click="importTemplate">下载模板</el-link>-->
        </div>
        <div class="el-upload__tip" style="color:red" slot="tip">提示：仅允许导入“xls”或“xlsx”格式文件！</div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listSfproduct,
  getSfproduct,
  delSfproduct,
  addSfproduct,
  updateSfproduct,
  listMaterials,
  getMiddle,
  addMaterials,
  updateMaterials,
  delMaterial, importTemplate, transmissionSfpID, overAgain
} from "@/api/sfproduct/sfproduct";
import {listMaterial} from "@/api/materials/material";
/** 获取token */
import { getToken } from "@/utils/auth";
export default {
  name: "Sfproduct",
  dicts: ['lw_self_produced'],
  data() {
    return {
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/sfproduct/sfproduct/importData"
      },
      selectable : false,
      sfpId :null,
      materials: [],
      value: '',
      table: false,
      gridData: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 半成品表格数据
      sfproductList: [],
      // 弹出层标题
      title: "",
      matTitle:"",
      // 是否显示弹出层
      open: false,
      matOpen: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        sfproductName: null,
        ifSelfProduced: null,
        model: null,
        parameter:null,
      },
      // 表单参数
      form: {},
      matForm:{},
      // 表单校验
      rules: {
        sfproductName: [
          { required: true, message: "元件名称不能为空", trigger: "blur" }
        ],
        ifSelfProduced: [
          { required: true, message: "是否自产不能为空", trigger: "change" }
        ],
      }
    };
  },
  created() {
    this.getList();
    this.getMaterialList();
  },
  methods: {
    overAgain(){
      this.getMaterials(this.sfpId);
      overAgain(this.sfpId);
      this.$modal.msgSuccess("清空成功");
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "用户导入";
      this.upload.open = true;
      transmissionSfpID(this.sfpId);
    },
    /** 下载模板操作 */
    importTemplate() {
      importTemplate().then(response => {
        this.download(response.msg);
      });
    },
// 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
// 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(response.msg, "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
// 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    /** 查询原材料列表 */
    getMaterialList() {
      this.loading = true;
      this.queryParams.pageSize = 1000;//查询列表大小
      listMaterial(this.queryParams).then(response => {
        this.materials = response.rows;
        // this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询元件清单 */
    getMaterials(sfpId){
      this.loading = true;
      this.table = true;
      this.sfpId = sfpId;
      listMaterials(sfpId).then(response => {
        this.gridData = response.rows;
        this.total = response.total;
        this.loading = false;
      })
      console.log(sfpId);
    },
    /** 查询半成品列表 */
    getList() {
      this.loading = true;
      listSfproduct(this.queryParams).then(response => {
        this.sfproductList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.matOpen = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        sfproductId: null,
        sfproductName: null,
        ifSelfProduced: null,
        model: null,
        parameter:null,
        remark: null
      };
      this.matForm = {
        sfproductId: null,
        materialId: null,
        quantity: null,
        bitNumber:null,
        ifExist:null
      };
      this.resetForm("matForm");
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.sfproductId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加半成品";
    },
    /** 新增原材料按钮操作 */
    materialAdd(){
      this.reset();
      this.selectable = false;
      this.matOpen = true;
      this.matForm.sfproductId = this.sfpId
      this.matForm.ifExist = false;
      this.matTitle = "添加原材料";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const sfproductId = row.sfproductId || this.ids
      getSfproduct(sfproductId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改半成品";
      });
    },
    /** 修改原材料按钮操作 */
    materialUpdate(row) {
      this.reset();
      this.selectable = true;
      const materialId =  row.materialId;
      getMiddle(this.sfpId,materialId).then(response => {
        this.matOpen = true;
        console.log(response);
        this.matForm = response;
        this.matForm.ifExist = true;
        this.title = "修改原材料";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.sfproductId != null) {
            updateSfproduct(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addSfproduct(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 元件清单提交按钮 */
    submitMatForm() {
      this.$refs["matForm"].validate(valid => {
          if (valid) {
            if (this.matForm.ifExist) {
              updateMaterials(this.matForm).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.matOpen = false;
                this.getMaterials(this.matForm.sfproductId);
              });
            } else {
              addMaterials(this.matForm).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.matOpen = false;
                this.getMaterials(this.matForm.sfproductId);
              });
            }
          }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const sfproductIds = row.sfproductId || this.ids;
      this.$modal.confirm('是否确认删除半成品编号为"' + sfproductIds + '"的数据项？').then(function() {
        return delSfproduct(sfproductIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 删除菜单元件操作 */
    materialDelete(row) {
      const sfproductId = this.sfpId;
      const materialId = row.materialId;
      console.log(sfproductId);
      console.log(materialId);
      this.$modal.confirm('是否确认删除原材料编号为"' + materialId + '"的数据项？').then(function() {
        return delMaterial(sfproductId,materialId);
      }).then(() => {
        this.getMaterials(sfproductId);
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('sfproduct/sfproduct/export', {
        ...this.queryParams
      }, `sfproduct_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
